package com.ljx.vod.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ljx.model.vod.Chapter;
import com.ljx.model.vod.Video;
import com.ljx.vo.vod.ChapterVo;
import com.ljx.vo.vod.VideoVo;
import com.ljx.vod.mapper.ChapterMapper;
import com.ljx.vod.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.vod.service.VideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author ljx
 * @since 2023-04-06
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private VideoService videoService;

    @Override
    public List<ChapterVo> getNestedTreeList(Long courseId) {

        LambdaQueryWrapper<Chapter> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Chapter::getCourseId,courseId);
        queryWrapper.orderByAsc(Chapter::getSort,Chapter::getId);
        List<Chapter> chapters = baseMapper.selectList(queryWrapper);

        LambdaQueryWrapper<Video> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Video::getCourseId,courseId);
        wrapper.orderByAsc(Video::getSort,Video::getId);
        List<Video> videos = videoService.list(wrapper);

        List<ChapterVo> chapterVos = chapters.stream().map(chapter -> {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter, chapterVo);
            ArrayList<VideoVo> list = new ArrayList<>();
            for (int i = 0; i < videos.size(); i++) {
                Video video = videos.get(i);
                if (chapter.getId().equals(video.getChapterId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video, videoVo);
                    list.add(videoVo);
                }
            }
            chapterVo.setChildren(list);
            return chapterVo;
        }).collect(Collectors.toList());
        return chapterVos;
    }

    @Override
    public void savaChapter(Chapter chapter) {
        baseMapper.insert(chapter);
    }

    @Override
    public void updateChapter(Chapter chapter) {
        baseMapper.updateById(chapter);
    }

    @Override
    public void removeChapter(Long id) {
        baseMapper.deleteById(id);
    }

    //根据课程id删除章节
    @Override
    public void removeChapterByCourseId(Long id) {
        QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",id);
        baseMapper.delete(wrapper);
    }
}
